#include "UserService.h"
#include "../../database/DatabaseUtil.h"
#include "../../sha256/SHA256.h"
#include "../../enum/StatusCode.h"
#include "../log/LogService.h"
#include <QDebug>

UserService &UserService::getInstance() {
    static UserService instance;
    return instance;
}

StatusCode UserService::login(User user) {
    json getUser = DatabaseUtil::getInstance().executeQuery("SELECT * FROM users WHERE username = ? AND isDeleted = 0",
                                                            {user.username.value_or("")});

    if (getUser.empty()) {
        return StatusCode::USER_NOT_EXIST;
    }

    User getUserEntity = User::fromJson(getUser[0]);
    if (SHA256::hash(user.password.value_or("")) != getUserEntity.password.value_or("")) {
        return StatusCode::PASSWORD_ERROR;
    }

    // 构造日志对象
    SystemLog log;
    log.content = "用户登录";
    log.userId = getUserEntity.userId.value_or(-1);
    LogService::getInstance().log(log);
    return StatusCode::OK;
}

StatusCode UserService::registerUser(User user) {
    json getUser = DatabaseUtil::getInstance().executeQuery("SELECT * FROM users WHERE username = ? AND isDeleted = 0",
                                                            {user.username.value_or("")});

    if (!getUser.empty()) {
        return StatusCode::USER_EXIST;
    }

    // 密码加密
    user.password = SHA256::hash(user.password.value_or(""));

    int result = DatabaseUtil::getInstance().executeUpdate(
        "INSERT INTO users (username, password, email, phone, role) VALUES (?, ?, ?, ?, ?)",
        {
            user.username.value_or(""),
            user.password.value_or(""),
            user.email.value_or(""),
            user.phone.value_or(""),
            user.role.value_or("")
        });

    if (result == -1) {
        return StatusCode::FAILED;
    }

    getUser = DatabaseUtil::getInstance().executeQuery("SELECT * FROM users WHERE username = ? AND isDeleted = 0",
                                                       {user.username.value_or("")});
    User getUserEntity = User::fromJson(getUser[0]);

    SystemLog log;
    log.content = "用户注册";
    log.userId = getUserEntity.userId.value_or(-1);
    LogService::getInstance().log(log);

    return StatusCode::OK;
}
